# -*- coding: utf-8 -*-
# @Time : 2022/2/15 11:25
# @Author : Administrator
# @Email : simple_days@qq.com
# @File : getDataZCv4tTree.py
# @Project : mongodb
# ©Copyright : 中国电建集团透平科技有限公司版权所有
# -*- coding: utf-8 -*-
# @Time : 2022/2/15 8:56
# @Author : Administrator
# @Email : simple_days@qq.com
# @File : getDataLGv4Tree.py
# @Project : mongodb
# ©Copyright : 中国电建集团透平科技有限公司版权所有
import xlrd
import json
import pymongo
from treelib.exceptions import DuplicatedNodeIdError


def readxlsfile(filename):
    """

    :param filename: 读取的excel文件名
    :return: list 表格中所有sheet列表
    """
    workbook = xlrd.open_workbook(filename)
    sheets = []
    for index in range(workbook.nsheets):
        sheets.append(workbook.sheet_by_index(index))
    return sheets


def zhuanyi(string):
    """
    转义字符串
    %c : ø

    :param string:
    :return:
    """
    if '%c' in string or '%x' in string or '"' in string:
        return string.replace('%c', 'ø').replace('%x', 'X').replace('"', '#').strip()

    return string


from treelib import Tree

tuhaoList = []


def readSheetToTree(sheet):
    if sheet.nrows <= 0:
        print(sheet.name)
        return

    tree = Tree()

    doc = {
        "文件名称": zhuanyi(sheet.cell_value(0, 1).strip()),
        "图纸编号": zhuanyi(sheet.cell_value(1, 1).strip()),
        "图纸名称": zhuanyi(sheet.cell_value(2, 1).strip()),
        "产品型号": zhuanyi(sheet.cell_value(3, 1).strip()),
        "材料名称": zhuanyi(sheet.cell_value(4, 1).strip()),
        "数量": sheet.cell_value(5, 1),
        "重量": sheet.cell_value(6, 1),
        "设计日期": sheet.cell_value(7, 1),

    }
    tuhaoList.append(doc['图纸编号'])
    tree.create_node(tag=doc['图纸编号'], identifier=doc['图纸编号'], data=doc)
    order = 0
    for i in range(9, sheet.nrows):
        row = []
        try:
            for j in range(9):
                row.append(sheet.cell_value(i, j))
        except IndexError:
            pass
            print(doc)

        order += 1
        zitu = {
            'order': order,
            '序号': row[0],
            '图纸编号': zhuanyi(row[1]),
            '名称': zhuanyi(row[2]),
            '数量': row[3],
            '材料': row[4],
            '单重': row[5],
            '总重': row[6],
            '备注': row[7],
            '来源': row[8],
        }

        if zitu['图纸编号'] == ' ':
            zitu['图纸编号'] = str(zitu['序号']).rstrip('.0') + zitu['名称']
        # if zitu['图纸编号'] == ' ' or 'W' in str(zitu['序号']):
        #     zitu['图纸编号'] = str(zitu['序号']).split('.')[0] + ' ' + (zitu['图纸编号'])
        #     print("doc['图纸编号']",doc['图纸编号'],"zitu['图纸编号']",zitu['图纸编号'])

        try:
            if zitu['图纸编号'].strip() == ' ' or 'W' in str(zitu['序号']) or zitu['图纸编号'] == '':
                print("隨機生成id", zitu['名称'])
                tree.create_node(tag=str(zitu['序号']).rstrip('.0') + zitu['名称'], data=zitu, parent=doc['图纸编号'])
            else:
                tree.create_node(tag=zitu['图纸编号'], identifier=zitu['图纸编号'], data=zitu, parent=doc['图纸编号'])
            # tree.create_node(tag=zitu['图纸编号'], identifier=zitu['图纸编号'], data=zitu, parent=doc['图纸编号'])
            for node in tree.all_nodes():
                if node.identifier == '1 ':
                    print("害群之馬", tree.show())

        except DuplicatedNodeIdError:
            tree.create_node(tag=zitu['图纸编号'], data=zitu, parent=doc['图纸编号'])
    return tree


treeList = []
maxDepth = 1


def genTree():
    global maxDepth
    for tree in treeList:
        for leaf in tree.leaves():
            if leaf.data['图纸编号'] in tuhaoList:
                print('该叶子节点{}存在子节点'.format(leaf.data['图纸编号']))
                # tree.show()
                # print("叶子节点",leaf.data)
                # print(leaf.identifier)
                for node in tree.all_nodes():
                    print(node.data)
                    print(node.identifier)

                index = tuhaoList.index(leaf.data['图纸编号'])
                try:
                    # print("zijiedian", treeList[index].show())
                    tree.merge(leaf.identifier, treeList[index])
                except ValueError as e:
                    print(tree.show())
                    print(e)

                # LG23600.merge(leaf.identifier,)
                # print('深度',tree.depth())

                tree_depth = tree.depth()
                if tree_depth > maxDepth:
                    maxDepth = tree.depth()
                # tree.show()
    return maxDepth


def saveTodb(db, docs):
    myclient = pymongo.MongoClient('mongodb://172.2.6.93:30002/')
    mydb = myclient['test']
    mycol = mydb[db]

    x = mycol.delete_many({})
    x = mycol.insert_many(docs)
    print(x.inserted_ids)


def run():
    sheets = readxlsfile('./主轴承完整nodes.xls')

    for sheet in sheets:
        treeList.append(readSheetToTree(sheet))

    print('====' * 20)
    index = tuhaoList.index('U236D00(G)')
    treeList[index].show(line_type='ascii-em')
    print(treeList[index].to_json(with_data=True).encode('utf-8').decode('unicode_escape'))
    genTree()
    genTree()
    treeList[index].show(line_type='ascii-em')
    print('====' * 20)
    print(treeList[index].to_json(with_data=True).encode('utf-8').decode('unicode_escape'))
    # for tree in treeList[0:20]:
    #
    #     if(tree.depth()>2):
    #         for node in tree.all_nodes_itr():
    #             print(node.data)
    #
    # index = tuhaoList.index('U236D00(G)')
    # print(treeList[index].show())


run()
